package com.hengxinguotong.zhihuichengjian.weekpicker;

import android.app.AlertDialog;
import android.content.Context;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.weekpicker.entity.MonthHelper;
import com.hengxinguotong.zhihuichengjian.weekpicker.entity.Week;
import com.hengxinguotong.zhihuichengjian.weekpicker.entity.WeekHelper;

import java.util.Calendar;
import java.util.List;

public class WeekPickerDialog extends AlertDialog implements View.OnClickListener{
    private static final String TAG = "WeekPickerDialog";

    private final OnWeekSelectListener onWeekSelectListener;
    private CustomNumberPicker yearPicker;
    private CustomNumberPicker monthPicker;
    private CustomNumberPicker weekPicker;
    private TextView okTv;
    private TextView cancelTv;
    private List<Integer> yearList;
    private List<Integer> monthList;
    private List<Week> weekList;
    private String[] yearDisplayValues;
    private String[] monthDisplayValues;
    private String[] weekDisplayValues;
    private int selectYearIndex;
    private int selectMonthIndex;
    private int selectWeekIndex;

    public interface OnWeekSelectListener {
        void onWeekSelect(Week week);
    }

    public WeekPickerDialog(Context context, OnWeekSelectListener listener) {
        this(context, R.style.dialog_no_action_bar, listener);
    }

    static int resolveDialogTheme(Context context, int resId) {
        if (resId == 0) {
            final TypedValue outValue = new TypedValue();
            context.getTheme().resolveAttribute(android.R.attr.timePickerDialogTheme, outValue, true);
            return outValue.resourceId;
        } else {
            return resId;
        }
    }

    public WeekPickerDialog(Context context, int themeResId, OnWeekSelectListener listener ) {
        super(context, resolveDialogTheme(context, themeResId));
        initData();
        onWeekSelectListener = listener;
        final Context themeContext = getContext();
        final LayoutInflater inflater = LayoutInflater.from(themeContext);
        final View view = inflater.inflate(R.layout.week_picker_dialog, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(params);
        yearPicker = (CustomNumberPicker) view.findViewById(R.id.yearPicker);
        monthPicker = (CustomNumberPicker) view.findViewById(R.id.monthPicker);
        weekPicker = (CustomNumberPicker) view.findViewById(R.id.weekPicker);
        okTv = (TextView) view.findViewById(R.id.ok_tv);
        okTv.setOnClickListener(this);
        cancelTv = (TextView) view.findViewById(R.id.cancel_tv);
        cancelTv.setOnClickListener(this);
        initPickerView();
        setView(view);
    }

    private void initPickerView(){
        yearPicker.setDisplayedValues(yearDisplayValues);
        yearPicker.setMinValue(0);
        yearPicker.setMaxValue(yearDisplayValues.length - 1);
        yearPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        yearPicker.setValue(selectYearIndex);
        yearPicker.setWrapSelectorWheel(true);//是否循环显示
        yearPicker.setNumberPickerDividerColor();
        yearPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                selectYearIndex = newVal;
                updateWearPickerValue();
            }
        });

        monthPicker.setDisplayedValues(monthDisplayValues);
        monthPicker.setMinValue(0);
        monthPicker.setMaxValue(monthDisplayValues.length - 1);
        monthPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        monthPicker.setValue(selectMonthIndex);
        monthPicker.setWrapSelectorWheel(true);
        monthPicker.setNumberPickerDividerColor();
        monthPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                selectMonthIndex = newVal;
                updateWearPickerValue();
            }
        });

        weekPicker.setDisplayedValues(weekDisplayValues);
        weekPicker.setMinValue(0);
        weekPicker.setMaxValue(weekDisplayValues.length - 1);
        weekPicker.setValue(selectWeekIndex);
        weekPicker.setWrapSelectorWheel(true);
        weekPicker.setNumberPickerDividerColor();
        weekPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        weekPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                selectWeekIndex = newVal;
            }
        });
    }

    private void updateWearPickerValue(){
        String[] yearValues = yearPicker.getDisplayedValues();
        String[] monthValues = monthPicker.getDisplayedValues();
        if (yearValues != null && monthValues != null) {
            weekList = WeekHelper.getWeeksByYearAndMonth(yearList.get(selectYearIndex), monthList.get(selectMonthIndex));
            String[] resultWeeks = weekListToArray(weekList);
            int selectWeekIndex = weekPicker.getValue();
            if(resultWeeks.length >= weekDisplayValues.length){
                try{
                    weekPicker.setDisplayedValues(resultWeeks);
                    weekPicker.setMinValue(0);
                    weekPicker.setMaxValue(resultWeeks.length - 1);
                    if(selectWeekIndex > resultWeeks.length -1){
                        selectWeekIndex = resultWeeks.length -1;
                    }
                    weekPicker.setValue(selectWeekIndex);
                    weekPicker.invalidate();
                }catch (Exception e){
                    e.printStackTrace();
                    weekPicker.setMinValue(0);
                    weekPicker.setMaxValue(resultWeeks.length - 1);
                    weekPicker.setDisplayedValues(resultWeeks);
                    if(selectWeekIndex > resultWeeks.length -1){
                        selectWeekIndex = resultWeeks.length -1;
                    }
                    weekPicker.setValue(selectWeekIndex);
                    weekPicker.invalidate();
                }
            }else {
                try{
                    weekPicker.setMinValue(0);
                    weekPicker.setMaxValue(resultWeeks.length - 1);
                    weekPicker.setDisplayedValues(resultWeeks);
                    if(selectWeekIndex > resultWeeks.length -1){
                        selectWeekIndex = resultWeeks.length -1;
                    }
                    weekPicker.setValue(selectWeekIndex);
                    weekPicker.invalidate();
                }catch (Exception e){
                    e.printStackTrace();
                    weekPicker.setDisplayedValues(resultWeeks);
                    weekPicker.setMinValue(0);
                    weekPicker.setMaxValue(resultWeeks.length - 1);
                    if(selectWeekIndex > resultWeeks.length -1){
                        selectWeekIndex = resultWeeks.length -1;
                    }
                    weekPicker.setValue(selectWeekIndex);
                    weekPicker.invalidate();
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ok_tv:
                Week week = weekList.get(selectWeekIndex);
                if (onWeekSelectListener != null) {
                    onWeekSelectListener.onWeekSelect(week);
                }
                cancel();
                break;
            case R.id.cancel_tv:
                cancel();
                break;
        }
    }

    private void initData(){
        selectYearIndex = 100;
        yearList = WeekHelper.getYears();
        yearDisplayValues = yearListToArray(yearList);

        selectMonthIndex = MonthHelper.getSelectMonth();
        monthList = WeekHelper.getMonths();
        monthDisplayValues = monthListToArray(monthList);

        weekList = WeekHelper.getWeeksByYearAndMonth(yearList.get(selectYearIndex), monthList.get(selectMonthIndex));
        weekDisplayValues = weekListToArray(weekList);
        selectWeekIndex = WeekHelper.getSelectWeekIndex(weekList);
    }

    private String[] yearListToArray(List<Integer> list){
        String[] strings = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strings[i] = list.get(i) + "年";
        }
        return strings;
    }

    private String[] monthListToArray(List<Integer> list){
        String[] strings = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strings[i] = (list.get(i) + 1) + "月";
        }
        return strings;
    }

    private String[] weekListToArray(List<Week> list){
        String[] strings = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strings[i] = list.get(i).toString();
        }
        return strings;
    }

}